<?php

function showphone($phone){
  return preg_replace("/(\d{1,3})\d\d\d\d(\d{3,4})/", "\$1****\$2", $phone);
}
//根据经纬度计算距离
function getDistance($lat1,$lng1,$lat2,$lng2) {
    //半径
    $R = 6378137;
    //将角度转为狐度
    $radLat1 = deg2rad($lat1);
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    //结果
    $s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;
    
    if(is_nan($s)) {
      $s = 0;
    }
    
    //精度
    $s = round($s* 10000,2)/10000;
    return  round($s/1000, 2);
}

//根据classid 获取当前入学年份
function getYearByCid($class_id) {
  if(date("m") < 9) {
    return date("Y") - $class_id;
  } else {
    return date("Y") - $class_id + 1;
  }
}

//根据入学年份 获取当前classid
function getCidByYear($year) {
  if($year == 0) {
    return 0;
  }
  
  if(date("m") < 9) {
    return date("Y") - $year;
  } else {
    return date("Y") - $year + 1;
  }
}

function xml_to_array($xml){
  $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
  if(preg_match_all($reg, $xml, $matches)){
    $count = count($matches[0]);
    for($i = 0; $i < $count; $i++){
    $subxml= $matches[2][$i];
    $key = $matches[1][$i];
      if(preg_match( $reg, $subxml )){
        $arr[$key] = xml_to_array( $subxml );
      }else{
        $arr[$key] = $subxml;
      }
    }
  }
  return $arr;
}

//正则匹配表情
function check_em($str)
{
  return preg_replace_callback('/\[[\x{4e00}-\x{9fa5}]*]/iu',function($matches){
    $key = $matches[0];
    $emobj = json_decode('{"[可爱]":"000","[笑脸]":"001","[囧]":"002","[生气]":"003","[鬼脸]":"004","[花心]":"005","[害怕]":"006","[我汗]":"007","[尴尬]":"008","[哼哼]":"009","[忧郁]":"010","[呲牙]":"011","[媚眼]":"012","[累]":"013","[苦逼]":"014","[瞌睡]":"015","[哎呀]":"016","[刺瞎]":"017","[哭]":"018","[激动]":"019","[难过]":"020","[害羞]":"021","[高兴]":"022","[愤怒]":"023","[亲]":"024","[飞吻]":"025","[得意]":"026","[惊恐]":"027","[口罩]":"028","[惊讶]":"029","[委屈]":"030","[生病]":"031","[红心]":"032","[心碎]":"033","[玫瑰]":"034","[花]":"035","[外星人]":"036","[金牛座]":"037","[双子座]":"038","[巨蟹座]":"039","[狮子座]":"040","[处女座]":"041","[天平座]":"042","[天蝎座]":"043","[射手座]":"044","[摩羯座]":"045","[水瓶座]":"046","[白羊座]":"047","[双鱼座]":"048","[星座]":"049","[男孩]":"050","[女孩]":"051","[嘴唇]":"052","[爸爸]":"053","[妈妈]":"054","[衣服]":"055","[皮鞋]":"056","[照相]":"057","[电话]":"058","[石头]":"059","[胜利]":"060","[禁止]":"061","[滑雪]":"062","[高尔夫]":"063","[网球]":"064","[棒球]":"065","[冲浪]":"066","[足球]":"067","[小鱼]":"068","[问号]":"069","[叹号]":"070","[顶]":"071","[写字]":"072","[衬衫]":"073","[小花]":"074","[郁金香]":"075","[向日葵]":"076","[鲜花]":"077","[椰树]":"078","[仙人掌]":"079","[气球]":"080","[炸弹]":"081","[喝彩]":"082","[剪子]":"083","[蝴蝶结]":"084","[机密]":"085","[铃声]":"086","[女帽]":"087","[裙子]":"088","[理发店]":"089","[和服]":"090","[比基尼]":"091","[拎包]":"092","[拍摄]":"093","[铃铛]":"094","[音乐]":"095","[心星]":"096","[粉心]":"097","[丘比特]":"098","[吹气]":"099","[口水]":"100","[对]":"101","[错]":"102","[绿茶]":"103","[面包]":"104","[面条]":"105","[咖喱饭]":"106","[饭团]":"107","[麻辣烫]":"108","[寿司]":"109","[苹果]":"110","[橙子]":"111","[草莓]":"112","[西瓜]":"113","[柿子]":"114","[眼睛]":"115","[好的]":"116"}');
    $name = $emobj->$key;
    return '<img src="/snow/Public/js/face/face/'.$name.'.png"/>';
  },$str);
}

/**
 *----------------------------------------------------------
 * 输出安全的html
 *----------------------------------------------------------
 * @static
 * @access public
 *----------------------------------------------------------
 * @param string $text 需要转换的字符串
 * @param string $tags 允许的标签
 *----------------------------------------------------------
 * @return string
 *----------------------------------------------------------
 */
function h($text, $tags = null) {
    //完全过滤注释
    $text = preg_replace('/<!--?.*-->/', '', $text);
    //css注释过滤
    $text = preg_replace('/\/\*.*?\*\//s', '', $text);

    //完全过滤动态代码
    $text = preg_replace('/<\?|\?'.'>/', '', $text);
    //完全过滤js
    $text = preg_replace('/<script?.*\/script>/', '', $text);

    $text = str_replace('[', '&#091;', $text);
    $text = str_replace(']', '&#093;', $text);
    $text = str_replace('|', '&#124;', $text);
    //过滤换行符
    $text = preg_replace('/\r?\n/', '', $text);
    //br
    $text = preg_replace('/<br(\s\/)?'.'>/i', '[br]', $text);
    $text = preg_replace('/(\[br\]\s*){10,}/i', '[br]', $text);
    //过滤危险的属性，如：过滤on事件lang js
    while(preg_match('/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i', $text, $mat)){
        $text=str_replace($mat[0], $mat[1], $text);
    }

    while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
        $text=str_replace($mat[0], $mat[1].$mat[3], $text);
    }

    if(empty($tags)) {
        $tags = 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a';
    }


    var_dump($text);
    //允许的HTML标签
    $text = preg_replace('/<(' . $tags . ')( [^><\[\]]*)>/i', '[\1\2]', $text);

    //过滤多余html
    $text = preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml)[^><]*>/i', '', $text);

    //过滤合法的html标签
    while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
        $text = str_replace($mat[0], str_replace('>', ']', str_replace('<', '[',$mat[0])), $text);
    }

    //转换引号
    while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i', $text, $mat)){
        $text = str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
    }
    //过滤错误的单个引号
    while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i', $text, $mat)){
        $text = str_replace($mat[0], str_replace($mat[1], '', $mat[0]), $text);
    }



    //转换其它所有不合法的 < >
    $text = str_replace('<', '&lt;', $text);
    $text = str_replace('>', '&gt;', $text);
    $text = str_replace('"', '&quot;', $text);
     //反转换
    $text = str_replace('[', '<', $text);
    $text = str_replace(']', '>', $text);
    $text = str_replace('|', '"', $text);
    //过滤多余空格
    $text = str_replace('  ', ' ', $text);

    return $text;
}

/**
 *+----------------------------------------------------------
 * 转换涉及XSS攻击的字符串
 *----------------------------------------------------------
 * @static
 * @access public
 *----------------------------------------------------------
 * @param string $val 需要转换的字符串
 *----------------------------------------------------------
 * @return string
 *----------------------------------------------------------
 */
function remove_xss($val) {
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
   // this prevents some character re-spacing such as <java\0script>
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
   $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

   // straight replacements, the user should never need these since they're normal characters
   // this prevents like <IMG SRC=@avascript:alert('XSS')>
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      // ;? matches the ;, which is optional
      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

      // @ @ search for the hex values
      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      // @ @ 0{0,7} matches '0' zero to seven times
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }

   // now the only remaining whitespace attacks are \t, \n, and \r
   $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
   $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);

   $found = true; // keep replacing as long as the previous round replaced something
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[xX]0{0,8}([9ab]);)';
               $pattern .= '|';
               $pattern .= '|(&#0{0,8}([9|10|13]);)';
               $pattern .= ')*';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
         if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
         }
      }
   }
   return strip_tags($val);
}

/*
* 字符串截取(支持中文字符串截取)
*
* @$str string 原始字符串
* @$start int 开始位置
* @$length int 从开始位置开始，截取的长度
* @$charset string 字符集
* @$suffix string 截取后串的后缀
*
* @use mSubStr('fdsafsadfas',0,5);
*/
function mSubStr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    if(function_exists("mb_substr")){
		mb_substr($str, $start, $length, $charset);
	}elseif(function_exists('iconv_substr')) {
		iconv_substr($str,$start,$length,$charset);
	}
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    
	preg_match_all($re[$charset], $str, $match);
	$slice = join("",array_slice($match[0], $start, $length));
	if($suffix) return $slice."…";
	
    return $slice;
}
